import React, { useState, useEffect } from 'react';
import { addCdnConfig, updateCdnConfig, deleteCdnConfig, queryAllCdnConfigs, deployCdn } from '../../api/cdnConfigApi';

interface CdnConfig {
  id: number;
  domain: string;
  originIp: string;
}

const CdnConfig = () => {
  const [domain, setDomain] = useState('');
  const [originIp, setOriginIp] = useState('');
  const [currentRecordId, setCurrentRecordId] = useState<number | null>(null);
  const [records, setRecords] = useState<CdnConfig[]>([]);
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    const fetchRecords = async () => {
      try {
        const fetchedRecords = await queryAllCdnConfigs();
        setRecords(fetchedRecords);
      } catch (error) {
        console.error('Error fetching CDN configurations:', error);
      }
    };
    fetchRecords();
  }, []);

  const handleAddRecord = async () => {
    if (currentRecordId !== null) {
      await updateCdnConfig(currentRecordId, { domain, originIp });
      setCurrentRecordId(null);
    } else {
      await addCdnConfig({ userId: 1, domain, originIp });
    }
    setDomain('');
    setOriginIp('');
    setShowModal(false);
  };

  const handleDeleteRecord = async (id: number) => {
    if (window.confirm("确定要删除这条记录吗？")) {
      await deleteCdnConfig(id);
    }
  };

  const handleDeploy = async (id: number) => {
    await deployCdn(id);
  };

  const handleEditRecord = (id: number) => {
    const record = records.find(record => record.id === id);
    if (record) {
      setDomain(record.domain);
      setOriginIp(record.originIp);
      setCurrentRecordId(id);
    }
    setShowModal(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleAddRecord();
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* 标题区 */}
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">CDN 配置管理</h1>
        <button
          className="bg-blue-600 text-white py-2 px-5 rounded-lg shadow hover:bg-blue-700 transition"
          onClick={() => setShowModal(true)}
        >
          + 新增
        </button>
      </div>

      <p className="mb-6 text-gray-700 dark:text-gray-300">
        在这里你可以添加、修改、删除和部署 CDN 配置。
      </p>

      {/* 表格 */}
      <div className="relative overflow-x-auto rounded-lg shadow">
        <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
          <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
            <tr>
              <th scope="col" className="px-6 py-3">ID</th>
              <th scope="col" className="px-6 py-3">CNAME</th>
              <th scope="col" className="px-6 py-3">源站 IP</th>
              <th scope="col" className="px-6 py-3 text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {records.map(record => (
              <tr
                key={record.id}
                className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 transition"
              >
                <td className="px-6 py-4">{record.id}</td>
                <td className="px-6 py-4">{record.domain}</td>
                <td className="px-6 py-4">{record.originIp}</td>
                <td className="px-6 py-4 flex justify-end space-x-2">
                  <button
                    className="bg-blue-500 text-white py-1.5 px-3 rounded-lg hover:bg-blue-600 transition"
                    onClick={() => handleEditRecord(record.id)}
                  >
                    编辑
                  </button>
                  <button
                    className="bg-red-500 text-white py-1.5 px-3 rounded-lg hover:bg-red-600 transition"
                    onClick={() => handleDeleteRecord(record.id)}
                  >
                    删除
                  </button>
                  <button
                    className="bg-green-500 text-white py-1.5 px-3 rounded-lg hover:bg-green-600 transition"
                    onClick={() => {
                      if (window.confirm("确定要部署吗？")) {
                        handleDeploy(record.id);
                      }
                    }}
                  >
                    部署
                  </button>
                </td>
              </tr>
            ))}
            {records.length === 0 && (
              <tr>
                <td colSpan={4} className="px-6 py-4 text-center text-gray-500">
                  暂无数据
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 弹窗 */}
      {showModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          {/* 背景遮罩 */}
          <div
            className="absolute inset-0 bg-black bg-opacity-40"
            onClick={() => setShowModal(false)}
          ></div>

          {/* 内容区 */}
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
              {currentRecordId !== null ? '编辑配置' : '新增配置'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label
                  htmlFor="domain"
                  className="block text-gray-700 dark:text-gray-300 mb-1"
                >
                  CNAME:
                </label>
                <input
                  type="text"
                  id="domain"
                  value={domain}
                  onChange={(e) => setDomain(e.target.value)}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label
                  htmlFor="originIp"
                  className="block text-gray-700 dark:text-gray-300 mb-1"
                >
                  源站 IP:
                </label>
                <input
                  type="text"
                  id="originIp"
                  value={originIp}
                  onChange={(e) => setOriginIp(e.target.value)}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div className="flex justify-end space-x-3 pt-2">
                <button
                  type="button"
                  className="bg-gray-400 text-white py-2 px-4 rounded-lg hover:bg-gray-500 transition"
                  onClick={() => setShowModal(false)}
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition"
                >
                  {currentRecordId !== null ? '保存修改' : '添加配置'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default CdnConfig;
